﻿
using System;
using System.Threading.Tasks;

namespace Magic.Redis;


/// <summary>
/// 提供Redis客户端操作类（基于CsRedisCore实现）
/// </summary>
public sealed partial class CsRedisCoreClient : IRedisClient
{
	/// <summary>
	/// Publish.
	/// </summary>
	/// <typeparam name="T"></typeparam>
	/// <param name="channel"></param>
	/// <param name="message"></param>
	/// <returns></returns>
	public long Publish<T>(string channel, T message)
	{
		string data = Serialize(message);
		try
		{
			return RedisHelper.Publish(channel, data);
		}
		catch (Exception ex)
		{
			Faild($"An exception occurs on Publish.channel={channel}&message={Serialize(message)}", ex);
			return default;
		}
	}

	/// <summary>
	/// PublishAsync.
	/// </summary>
	/// <typeparam name="T"></typeparam>
	/// <param name="channel"></param>
	/// <param name="message"></param>
	/// <returns></returns>
	public Task<long> PublishAsync<T>(string channel, T message)
	{
		string data = Serialize(message);
		try
		{
			return RedisHelper.PublishAsync(channel, data);
		}
		catch (Exception ex)
		{
			Faild($"An exception occurs on PublishAsync.channel={channel}&message={Serialize(message)}", ex);
			return default;
		}
	}

	/// <summary>
	/// Subscribe.
	/// </summary>
	/// <typeparam name="T"></typeparam>
	/// <param name="channel"></param>
	/// <param name="handler"></param>
	public void Subscribe<T>(string channel, Action<T> handler)
	{
		try
		{
			RedisHelper.Subscribe((channel, (CSRedis.CSRedisClient.SubscribeMessageEventArgs msg) =>
			{
				handler(Deserialize<T>(msg.Body));
			}
			));
		}
		catch (Exception ex)
		{
			Faild($"An exception occurs on Subscribe.channel={channel}", ex);
		}
	}
}
